package org.nashua.tt151.dashboard;

import com.sun.squawk.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;

public class Connection {
        protected SocketConnection sock;
        private InputStreamReader reader;
	private BufferedWriter writer;
        private ConnectionListener listener;
	protected Timer t = new Timer();
        protected String[][] str = new String[0][0];
	public Connection(String host, int port, ConnectionListener cl) throws Exception {
		super();
		if (cl!=null) setConnectionListener(cl);
		final Connection con = this;
		sock = (SocketConnection) Connector.open("socket://"+host+":"+port);
                reader = new InputStreamReader(sock.openDataInputStream());
		writer = new BufferedWriter(new OutputStreamWriter(sock.openOutputStream()));
		t.schedule(new TimerTask(){
                    public void run() {
                        while (true) {
                            /* Check For Data And Remove Old Connections */
                            try {
                                if (reader.ready()) {
                                    char[] buffer = new char[24];
                                    reader.read(buffer);
                                    String stri = "";
                                    for (int i=0;i<buffer.length;i++) stri+=buffer[i]=='\0'?"":""+buffer[i];
                                    if (stri!=null) con.onDataRecieved(stri);
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
		},1);
		onConnect();
	}
	public void sendData(String str){
            try {
                writer.write(str);
                writer.newLine();
                writer.flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
	}
	public void disconnect() {
            try {
                sock.close();
            } catch (IOException e) {
            }
	}
        public void setConnectionListener(ConnectionListener cl){
            listener=cl;
	}
	protected void onConnect() {
            listener.onConnect();
	}
	protected void onDisconnect() {
            listener.onDisconnect();
	}
	protected void onDataRecieved(String str){
            if (str.startsWith("RETURN")) {
                update(str.substring(str.indexOf(",")+1,str.indexOf("&")),str.substring(str.indexOf("&")+1));
            } else {
                listener.onDataRecieved(str);
            }
	}
        public String requestData(String req) {
            String stri=null;
            while ((stri=grab(req))==null) {System.out.println("Waiting");}
            return stri;
        }
        public String grab(String key) {
            for (int i=0;i<str.length;i++)
                if (str[i][0].equals(key))
                    return str[i][1];
            return null;
        }
        public void update(String key,String value) {
            for (int i=0;i<str.length;i++) {
                if (str[i][0].equals(key)) {
                    if (value==null) {
                        str[i]=null;
                        clean();
                    } else {
                        str[i][1]=value;
                    }
                    return;
                }
            }
            add(key,value);
        }
        public void add(String key, String value){
            clean();
            String[][] strr = new String[str.length+1][2];
            for (int i=0;i<str.length;i++) strr[i]=str[i];
            strr[str.length] = new String[]{key,value};
            str=strr;
        }
        public void clean() {
            int c=0;
            for (int i=0;i<str.length;i++) c+=str[i]!=null?1:0;
            String[][] strr = new String[c][2];
            int x=0;
            for (int i=0;i<str.length;i++) if (str[i]!=null) {strr[x]=str[i];x++;}
            str=strr;
        }
}
